<?php
include_once('./config/config.php');

// 判断有没有表单提交
if ($_POST) {
  // 接收全部参数
  if ($_POST['action'] == 'change') {
    $name = $_POST['name'];
    $sql = "select * from department where name = '$name'";
    $dep = findOne($sql);
    if (!empty($dep)) {
      error("该部门已存在");
    } else {
      success("可以使用");
    }
  }

  $name = $_POST['dep'];
  $sql = "select * from department where name = '$name'";
  $dep = findOne($sql);
  if ($dep) {
    error('该部门已存在');
  }
  $data = [
    'name' => $name
  ];
  $i = insert('department', $data);
  if ($i) {
    ShowMsg("添加部门成功", "departmentList.php");
  } else {
    ShowMsg("添加部门失败");
  }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- 引入 -->
  <?php include_once('./common/meta.php') ?>
</head>

<body>
  <!--<![endif]-->

  <!-- 引入头部导航 -->
  <?php include_once('./common/navbar.php') ?>

  <!-- 引入侧边菜单栏 -->
  <?php include_once('./common/sidebar.php') ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">添加部门</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="index.php">Home</a> <span class="divider">/</span></li>
      <li class="active">addDepartment</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">
        <div class="btn-toolbar">
          <button class="btn btn-primary" onClick="location='departmentList.php'"><i class="icon-list"></i> 返回列表</button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form method="post" enctype="multipart/form-data">
                <!-- 部门名称 -->
                <label>部门名称</label>
                <input type="text" class="input-xxlarge depName" name="dep" id="depname" placeholder="请输入部门名称" required>
                <span id="msg"></span>
                <br>
                <button class="btn btn-primary" id="subBtn" value="提交">提交</button>
              </form>
            </div>
          </div>
        </div>

        <!-- 引入底部 -->
        <?php include_once('./common/footer.php') ?>

      </div>
    </div>
  </div>

</body>

</html>
<!-- 引用公共js文件 -->
<?php include_once('./common/script.php') ?>
<script>
  $(document).ready(function() {
    // 监听输入框值的变化 
    $('.depName').change(function() {
      let name = $(".depName").val()
      $.ajax({
        type: 'post',
        url: 'addDepartment.php',
        data: {
          name,
          action: 'change'
        },
        dataType: 'json',
        success: function(res) {
          if (res.code === 1) {
            $("#msg").text(res.msg).css({"color": "blue"})
          } else {
            $("#msg").text(res.msg).css({"color": "red"})
          }
        },
        error: function(err) {
          console.log("err")
        }
      })
    })
  })
</script>